# -*- coding:utf-8 -*-
import random


def probability_distribution_url(article_infos):
    """return the probability distribution of url according to pv
    """
    urls = [one['href'] for one in article_infos]
    read_nums = [int(one['read_num']) for one in article_infos]

    total_read_nums = sum(read_nums)
    url_with_pv_dict = [(url, read_num) for url, read_num in zip(urls, read_nums)]
    sorted_url_with_pv_dict = sorted(url_with_pv_dict)
    sorted_read_nums = [one[1] for one in sorted_url_with_pv_dict]  # 排序后的阅读量列表
    sorted_urls = [one[0] for one in sorted_url_with_pv_dict]  # 排序后的url列表

    probabilitys = [read_num/total_read_nums for read_num in sorted_read_nums]
    sorted_url_with_prob = [(url, prob) for url, prob in zip(sorted_urls, probabilitys)]
    return sorted_url_with_prob


def get_random_url_arrcording_to_pv(sorted_url_with_prob):
    """provide random url of article according to its page view
    """
    urls = [one[0] for one in sorted_url_with_prob]
    probs = [one[1] for one in sorted_url_with_prob]

    accumulate_probs = [sum(probs[0:i+1]) for i in range(len(probs))]  # 累积概率密度列表
    r = random.random()
    # generate random url according to accumulate_probs
    if r <= accumulate_probs[0]:
        return(urls[0])
    else:
        for index in range(1, len(accumulate_probs)):
            if (r > accumulate_probs[index-1]) and (r <= accumulate_probs[index]):
                return urls[index]
